package com.zmc.common.utils.token.impl;


import com.zmc.common.constant.AuthConstants;
import com.zmc.common.constant.CacheConstants;
import com.zmc.common.constant.Constants;
import com.zmc.common.domain.vo.member.MemberInfo;
import com.zmc.common.domain.vo.user.UserInfo;
import com.zmc.common.exception.token.TokenExpireException;
import com.zmc.common.utils.ServletUtils;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.redis.RedisCache;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.common.utils.uuid.IdUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author：zmc
 * @Date：2024/10/10 16:51
 */

@Component
public class AuthTokenServiceImpl implements AuthTokenService {


    private static final Logger log = LoggerFactory.getLogger(AuthTokenServiceImpl.class);

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    @Override
    public UserInfo getUserInfo() {
        // 获取请求携带的令牌
        String token = getToken(ServletUtils.getRequest());
        if (StringUtils.isEmpty(token)) {
            throw new TokenExpireException();
        }
        Claims claims = parseToken(token);
        // 解析对应的权限以及用户信息
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = getTokenKey(uuid);
        UserInfo user = redisCache.getCacheObject(userKey);
        //缓存获取失败，token过期
        if (user == null) {
            throw new TokenExpireException();
        }
        verifyToken(user);
        return user;
    }

    /**
     * 设置用户身份信息
     */
    @Override
    public void setUserInfo(UserInfo loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    @Override
    public void delUserInfo(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param userInfo 用户信息
     * @return 令牌
     */
    @Override
    public String createToken(UserInfo userInfo) {
        String token = IdUtils.fastUUID();
        userInfo.setToken(token);
        refreshToken(userInfo);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param userInfo
     * @return 令牌
     */
    @Override
    public void verifyToken(UserInfo userInfo) {
        long expireTime = userInfo.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(userInfo);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    @Override
    public void refreshToken(UserInfo loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + AuthConstants.JWT_EXPIRE_TIME * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, AuthConstants.JWT_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    @Override
    public MemberInfo getMemberInfo() {
        // 获取请求携带的令牌
        String token = getToken(ServletUtils.getRequest());
        if (Objects.isNull(token)) {
            throw new TokenExpireException();
        }
        Claims claims = parseToken(token);
        // 解析对应的权限以及用户信息
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = getTokenKey(uuid);
        MemberInfo member = redisCache.getCacheObject(userKey);
        //缓存获取失败，token过期
        if (member == null) {
            throw new TokenExpireException();
        }
        verifyToken(member);
        return member;
    }

    @Override
    public String createToken(MemberInfo memberInfo) {
        String token = IdUtils.fastUUID();
        memberInfo.setToken(token);
        refreshToken(memberInfo);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    @Override
    public void setMemberInfo(MemberInfo memberInfo) {
        if (StringUtils.isNotNull(memberInfo) && StringUtils.isNotEmpty(memberInfo.getToken())) {
            refreshToken(memberInfo);
        }
    }

    @Override
    public void delMemberInfo(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String memberKey = getTokenKey(token);
            redisCache.deleteObject(memberKey);
        }
    }

    @Override
    public void verifyToken(MemberInfo memberInfo) {
        long expireTime = memberInfo.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(memberInfo);
        }
    }

    @Override
    public void refreshToken(MemberInfo memberInfo) {
        memberInfo.setLoginTime(System.currentTimeMillis());
        memberInfo.setExpireTime(memberInfo.getLoginTime() + AuthConstants.JWT_EXPIRE_TIME * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(memberInfo.getToken());
        redisCache.setCacheObject(userKey, memberInfo, AuthConstants.JWT_EXPIRE_TIME, TimeUnit.MINUTES);
    }


    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(AuthConstants.JWT_SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌token
     */
    public String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, AuthConstants.JWT_SECRET).compact();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */

    @Override
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(AuthConstants.JWT_HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }
}
